package com.qfedu.utils;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;


public class ImageCodeUtil {
	
	private static String codeNum;//验证码
	/**
	 * 获取验证码图片
	 * @return
	 */
	public static BufferedImage getBufferedImage(){
		int charNum = 4;
		int width = 30 * 4;
		int height = 30;
		//1,创建内存对象
		BufferedImage bufferedImage = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);

		//2,获取绘图对象
		Graphics graphics = bufferedImage.getGraphics();
		//3,绘制背景颜色
		graphics.setColor(Color.LIGHT_GRAY);
		graphics.fillRect(0, 0, width, height);
		//绘制边框
		graphics.setColor(Color.BLUE);
		graphics.drawRect(0, 0, width - 1, height - 1);
		//设置验证码文字样式
		graphics.setColor(Color.BLACK);
		graphics.setFont(new Font("宋体", Font.BOLD, 23));

		//设置验证码文字内容
		Graphics2D graphics2d = (Graphics2D) graphics;
		String s = "ABCDEFGHIGKLMNOPQRSTUVWXYZ";
		Random random = new Random();
		String msg = "";
		int x = 5;
		for (int i = 0; i < 4; i++) {
			int index = random.nextInt(26);//0-25
			String content = String.valueOf(s.charAt(index));
			msg += content;
			double theta = random.nextInt(45) * Math.PI / 180;
			graphics2d.rotate(theta, x, 18);
			graphics2d.drawString(content, x, 18);
			graphics2d.rotate(-theta, x, 18);
			x += 30;
		}
		codeNum = msg;


		for (int i = 0; i < 10; i++) {

			int r = random.nextInt(255);
			int g = random.nextInt(255);
			int b = random.nextInt(255);
			graphics.setColor(new Color(r, g, b));
			int x1 = random.nextInt(width);
			int x2 = random.nextInt(width);

			int y1 = random.nextInt(height);
			int y2 = random.nextInt(height);
			graphics.drawLine(x1, y1, x2, y2);
		}
		//释放资源
		graphics.dispose();
//		ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
		return bufferedImage;
	}

	
	/**
	 * 返回验证码
	 * @return
	 */
	public static String getCodeNum() {
		return codeNum;
	}

}
